package org.ragdollcat.first.aop;

import cn.hutool.core.util.StrUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.ragdollcat.first.constants.UserConstant;
import org.ragdollcat.first.exception.ErrorCode;
import org.ragdollcat.first.exception.ThrowUtils;
import org.ragdollcat.first.model.annotation.AuthCheck;
import org.ragdollcat.first.model.entity.User;
import org.ragdollcat.first.service.UserService;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class CheckAuthAspect {

    @Resource
    private UserService userService;

    /**
     * 环绕通知，切加入了@authCheck的方法
     * @param joinPoint
     * @param authCheck
     * @return
     */
    @Around("@annotation(authCheck)")
    public Object checkAuth(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String mustRole = authCheck.mustRole();
        //如果为空，证明不需要进行权限校验
        if (StrUtil.isBlank(mustRole)){
            return joinPoint;
        }
        //获取当前登录人
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        User user = (User) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);

        ThrowUtils.throwIf(ObjectUtils.isEmpty(user), ErrorCode.NOT_LOGIN_ERROR,"请先登录！");

        //校验权限
        ThrowUtils.throwIf(!user.getUserRole().equals(mustRole),ErrorCode.NO_AUTH_ERROR,"您没有操作权限！");

        return joinPoint.proceed();
    }
}
